package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ArticleHomeMapper;
import com.heima.article.service.ArticleUploadFreeMarkerHtml;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojo.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 张一恒
 * @version 1.0
 * @description: 上传发布后的文章到minio
 * @date 2023/1/15 22:12
 */
@Service
@Slf4j
public class ArticleUploadFreeMarkerHtmlImpl implements ArticleUploadFreeMarkerHtml {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ArticleHomeMapper articleHomeMapper;


    @Override
    @Async
    public void uploadFreeMarkerHtml(ApArticle article, String content) {

        try {
            //配置freemarker
            Configuration configuration = new Configuration(Configuration.getVersion());

            //加载模板
            //选指定模板路径,classpath下templates下
            //得到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //设置字符编码
            configuration.setDefaultEncoding("utf-8");

            //指定模板文件名称
            Template template = configuration.getTemplate("article.ftl");

            //准备数据

            Map<String, Object> map = new HashMap<>();
            map.put("content", JSONArray.parseArray(content));

            //静态化
            //参数1：模板，参数2：数据模型
            String result = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            System.out.println(result);

            InputStream inputStream = IOUtils.toInputStream(result);
            //上传到minio
            String htmlFile = fileStorageService.uploadHtmlFile("", article.getId() + ".html", inputStream);

            //4.4 修改ap_article表，保存static_url字段
            ApArticle article_u = new ApArticle();
            article_u.setStaticUrl(htmlFile);
            articleHomeMapper.update(article_u,Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId,article.getId()));

            log.info("文章上传到分布式文件系统成功：{}",htmlFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
